import 'package:flutter/material.dart';
import 'package:hm_pda_app/pages/home.dart';
import 'package:hm_pda_app/config/http_request.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';
import 'package:hm_pda_app/pages/camera_upload_widget.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:hm_pda_app/router/auth_provider.dart';
import 'package:hm_pda_app/router/route_guard.dart';
import 'package:hm_pda_app/router/splash_screen.dart';
import 'package:shared_preferences/shared_preferences.dart';
// 路由引入
import 'package:hm_pda_app/pages/incoming_goods.dart';
import 'package:hm_pda_app/pages/pending_reinspection.dart';
import 'package:hm_pda_app/pages/pending_delivery.dart';
import 'package:hm_pda_app/pages/stocking_and_warehousing.dart';
import 'package:hm_pda_app/pages/picking_goods.dart';
import 'package:hm_pda_app/pages/packing_goods.dart';
import 'package:hm_pda_app/pages/weighing_goods.dart';
import 'package:hm_pda_app/pages/outbound_inspection.dart';
import 'package:hm_pda_app/pages/pickup_goods.dart';
import 'package:hm_pda_app/pages/warehouse_relocation.dart';
import 'package:hm_pda_app/pages/inventory_check.dart';
import 'package:hm_pda_app/pages/inventory_inquiry.dart';
import 'package:hm_pda_app/pages/inventory_log.dart';
import 'package:hm_pda_app/pages/instock_defects.dart';
import 'package:hm_pda_app/pages/exchange.dart';
import 'package:hm_pda_app/pages/incoming_goods_inquiry.dart';
import 'package:hm_pda_app/pages/login.dart';

//import 'package:flutter_dotenv/flutter_dotenv.dart';
//import 'package:hm_pda_app/camera_upload_widget.dart';
//import 'package:flutter/rendering.dart';
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  const env = String.fromEnvironment('ENV', defaultValue: 'development');
  final prefs = await SharedPreferences.getInstance();
  var isLoggedIn = prefs.getBool('isLoggedIn') ?? false;

  print('isLoggedIn: $isLoggedIn');
  String envFile;
  switch (env) {
    case 'production':
      envFile = '.env.production';
      break;
    case 'staging':
      envFile = '.env.staging';
      break;
    default:
      envFile = '.env.development';
  }
  print('envFile: $envFile');
  await dotenv.load(fileName: envFile);
  await initializeApp();
  // ChangeNotifierProvider(create: (context)=>ImageUploadNotifier(),child: const MyApp(),);
  runApp(
    MultiProvider(
      providers: [
        ChangeNotifierProvider(create: (context) => ImageUploadNotifier()),
        ChangeNotifierProvider(create: (context) => AuthProvider()),
      ],
      child: MyApp(isLoggedIn: isLoggedIn),
    ),
  );

  //设置Android头部的导航栏透明
  SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(
    statusBarColor: Colors.transparent,
  );
  SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
}

Future<void> initializeApp() async {
  try {
    // 初始化 HTTP 工具
    await HttpUtil.initialize(
      // baseUrl: 'http://192.168.100.233/test-api',
      // timeout: Duration(seconds: 15),
      // headers: {
      //   'User-Agent': 'YourApp/1.0.0',
      //   'X-Platform': 'flutter',
      // },
      // token: '初始token', // 如果有的话
    );

    print('✅ 应用初始化完成');
  } catch (e) {
    print('❌ 应用初始化失败: $e');
  }
}

class MyApp extends StatefulWidget {
  const MyApp({super.key, required this.isLoggedIn});

  final bool isLoggedIn;

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
    // 在initState中触发AuthProvider的autoLogin
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Provider.of<AuthProvider>(context, listen: false).autoLogin();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Consumer<AuthProvider>(
      builder: (context, auth, child) {
        return MaterialApp(
          title: '海麦PDA',
          theme: ThemeData(
            useMaterial3: true,
            visualDensity: VisualDensity.adaptivePlatformDensity,
          ),
          builder: (context, child) {
            return MediaQuery(
              data: MediaQuery.of(context).copyWith(
                textScaler: TextScaler.linear(
                  MediaQuery.of(context).textScaler.scale(1.0).clamp(0.8, 1.2),
                ),
              ),
              child: child!,
            );
          },
          onGenerateRoute: (settings) {
            // 路由守卫检查
            final redirect = RouteGuard.redirect(context, auth);
            print('redirect: $redirect,${settings.name}');

            // 判断isLoggedIn是否为true，不为true时进到登录页
            if (!widget.isLoggedIn) {
              return MaterialPageRoute(
                builder: (context) => _buildRoute('/Login'),
              );
            }

            if (redirect != null) {
              return MaterialPageRoute(
                builder: (context) => _buildRoute(redirect),
              );
            } else if (settings.name != null) {
              return MaterialPageRoute(
                builder: (context) => _buildRoute(settings.name!),
              );
            }

            return MaterialPageRoute(
              builder: (context) => _buildRoute('/Home'),
            );
          },
          initialRoute: '/Splash',
        );
      },
    );
  }

  Widget _buildRoute(String routerName) {
    switch (routerName) {
      case '/IncomingGoodsPage':
        return IncomingGoodsPage();
      case '/PendingReinspectionScreen':
        return PendingReinspectionScreen();
      case '/PendingDelivery':
        return PendingDelivery();
      case '/StockingAndWarehousingPage':
        return StockingAndWarehousingPage();
      case '/PickingGoods':
        return PickingGoods();
      case '/WeighingGoods':
        return WeighingGoods();
      case '/OutboundInspection':
        return OutboundInspection();
      case '/PickupGoods':
        return PickupGoods();
      case '/WarehouseRelocation':
        return WarehouseRelocation();
      case '/InventoryCheck':
        return InventoryCheck();
      case '/InventoryInquiry':
        return InventoryInquiry();
      case '/InventoryLog':
        return InventoryLog();
      case '/InstockDefects':
        return InstockDefects();
      case '/Exchange':
        return Exchange();
      case '/IncomingGoodsInquiry':
        return IncomingGoodsInquiry();
      case '/PackingGoods':
        return PackingGoods();
      case '/Home':
        return HomePage();
      case '/':
        return HomePage();
      case '/Splash':
        return const SplashScreen();
      case '/Login':
        return const Login();
      default:
        return Login();
    }
  }
}

// 主页，包含底部导航栏,现在不需要这个导航栏
class MainTabPage extends StatefulWidget {
  const MainTabPage({super.key});

  @override
  State<MainTabPage> createState() => _MainTabPageState();
}

class _MainTabPageState extends State<MainTabPage> {
  int _currentIndex = 0;
  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 2,
      child: Scaffold(
        appBar: null, // 不显示顶部的AppBar
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: _currentIndex,
          onTap: (index) {
            setState(() {
              _currentIndex = index;
            });
          },
          items: const [
            BottomNavigationBarItem(icon: Icon(Icons.home), label: '首页'),

            BottomNavigationBarItem(icon: Icon(Icons.login), label: '个人中心'),
          ],
        ),
        body: IndexedStack(
          index: _currentIndex,
          children: const [
            // RegisterFormPage(),
            // 可以在这里添加其他页面，如注册和登录页面
            Center(child: HomePage()), // 占位
            Center(child: Text('登录页面')), // 占位
          ],
        ),
      ),
    );
  }
}
